
package com.yyfax.ph.home.recommendloan;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.widget.ImageView;
import butterknife.BindView;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.ph.R;
import com.yyfax.ph.base.BaseYYFaxActivity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.GlobalVariableConfig;
import com.yyfax.ph.common.utils.preferenceutils.PreferenceConstants;
import com.yyfax.ph.home.recommendloan.basicinfo.BasicInfoFragment;
import com.yyfax.ph.home.recommendloan.creditinfo.UploadCreditPaperFragment;
import com.yyfax.ph.home.recommendloan.otherinfo.OtherInfoFragment;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 推荐贷款主界面
 * {@link BasicInfoFragment 基本资料}
 * {@link UploadCreditPaperFragment 征信报告或征信授权上传}
 * {@link OtherInfoFragment 其他信息资料}
 */
public class RecommendLoanActivity extends BaseYYFaxActivity {
	public static final String TAG = RecommendLoanActivity.class.getSimpleName();

	public static final int MSG_GET_SCAN_ID_CARD = 0x11;

	private static final String CURRENT_INDEX = "current_index";
	private static final String BUNDLE_KEY_RCM_ID = "bundle_key_rcm_id";
	private static final String BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT = "bundle_key_extra_params_to_upload_credit";

	private final static String BASIC_INFO_TAG = "base_info_fragment";
	private final static String UPLOAD_CREDIT_PAPER_TAG = "no_credit_fragment";
	private final static String OTHER_INFO_TAG = "supply_info_fragment";

	public final static int PAGE_BASIC_INFO = 1;
	public final static int PAGE_UPLOAD_CREDIT = 2;
	public final static int PAGE_OTHER_INFO = 3;
	private int mCurrentPage = PAGE_BASIC_INFO;

	private UploadCreditPaperFragment.ExtraParamsToUploadCredit mExtraParamsToUploadCredit = null;
	private String mRcmId = "";

	@BindView(R.id.base_info_step_iv)
	ImageView mStepImg;//步骤图片

	public static void start(Activity activity) {
		Intent intent = new Intent(activity, RecommendLoanActivity.class);
		activity.startActivity(intent);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(CURRENT_INDEX, mCurrentPage);
		if (mExtraParamsToUploadCredit != null) {
			outState.putParcelable(BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT, mExtraParamsToUploadCredit);
		}
		if (!TextUtils.isEmpty(mRcmId)) {
			outState.putString(BUNDLE_KEY_RCM_ID, mRcmId);
		}
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

	private void readBundle(Bundle bundle) {
		if (bundle != null) {
			mCurrentPage = bundle.getInt(CURRENT_INDEX, PAGE_BASIC_INFO);
			mExtraParamsToUploadCredit = bundle.getParcelable(BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT);
			mRcmId = bundle.getString(BUNDLE_KEY_RCM_ID);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		EventAgent.register(this);
		if (null != savedInstanceState) {
			readBundle(savedInstanceState);
		}
		showFragment(mCurrentPage, null);
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (GlobalVariableConfig.isThirdPartyPageOpened()) {
			GlobalVariableConfig.setIgnoreGestureFlag(false);
			GlobalVariableConfig.setThirdPartyPageOpenedFlag(false);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void pretreatmentAfterSetBaseView() {
		super.pretreatmentAfterSetBaseView();
	}

	@Override
	public int getContentViewRes() {
		return R.layout.recommend_loan_activity;
	}

	@Override
	public void initContentView() {
		setTopBarDividerViewVisible(false);
		setBtnBackVisible(true);
		setTitleVisible(true);
		setTitle(R.string.recommend_loan);
		setTitleLeftVisible(false);
		setBtnRightVisible(false);

		setBtnBackBackground(R.drawable.ic_black_back);
		setTopBarBackgroundColor(ContextCompat.getColor(this, R.color.color_white));
		setTitleCenterColor(ContextCompat.getColor(this, R.color.color_000000));
	}

	public void showFragment(int page, Object argument) {
  		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		Fragment basicInfoFragment = fm.findFragmentByTag(BASIC_INFO_TAG);
		Fragment uploadCreditPaperFragment = fm.findFragmentByTag(UPLOAD_CREDIT_PAPER_TAG);
		Fragment otherInfoFragment = fm.findFragmentByTag(OTHER_INFO_TAG);
		if (basicInfoFragment != null) {
			ft.hide(basicInfoFragment);
		}
		if (uploadCreditPaperFragment != null) {
			ft.hide(uploadCreditPaperFragment);
		}
		if (otherInfoFragment != null) {
			ft.hide(otherInfoFragment);
		}
		switch (page) {
			case PAGE_BASIC_INFO:
				if (basicInfoFragment == null) {
					basicInfoFragment = BasicInfoFragment.newInstance();
					ft.add(R.id.recommend_loan_container, basicInfoFragment, BASIC_INFO_TAG);
				} else {
					ft.show(basicInfoFragment);
				}
				mStepImg.setImageResource(R.drawable.ic_step_basic_info);
				mCurrentPage = page;
				break;
			case PAGE_UPLOAD_CREDIT:

				if (argument != null && argument instanceof UploadCreditPaperFragment.ExtraParamsToUploadCredit){
					mExtraParamsToUploadCredit = (UploadCreditPaperFragment.ExtraParamsToUploadCredit) argument;
				}
				if (uploadCreditPaperFragment == null) {
					uploadCreditPaperFragment = UploadCreditPaperFragment.newInstance(mExtraParamsToUploadCredit);
					ft.add(R.id.recommend_loan_container, uploadCreditPaperFragment, UPLOAD_CREDIT_PAPER_TAG);
				} else {
					((UploadCreditPaperFragment)uploadCreditPaperFragment).changeFragment(mExtraParamsToUploadCredit);
					ft.show(uploadCreditPaperFragment);
				}
				mStepImg.setImageResource(R.drawable.ic_step_credit_upload);
				mCurrentPage = page;
				break;
			case PAGE_OTHER_INFO:
				if (otherInfoFragment == null) {
					if (argument != null && argument instanceof String){
						mRcmId = (String) argument;
					}

					otherInfoFragment = OtherInfoFragment.newInstance(mRcmId);
					ft.add(R.id.recommend_loan_container, otherInfoFragment, OTHER_INFO_TAG);
				} else {
					ft.show(otherInfoFragment);
				}
				mStepImg.setImageResource(R.drawable.ic_step_supply_info);
				mCurrentPage = page;
				break;
			default:
				break;
		}
		YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_RECOMMEND_FAILED_INDEX, mCurrentPage);
		ft.commitAllowingStateLoss();
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onMessageEvent(PageDownEvent event) {
		pageDown(event.page, event.argument);
	}

	private void pageUp() {
		// 如果回退到征信页时,征信页已被回收,则回到基本资料页重新开始.
		FragmentManager fm = getSupportFragmentManager();
		OtherInfoFragment fragment = (OtherInfoFragment) fm.findFragmentByTag(OTHER_INFO_TAG);
		if (fragment == null) {
			mCurrentPage = PAGE_BASIC_INFO;
		}

		switch (mCurrentPage) {
			case PAGE_UPLOAD_CREDIT:
				showFragment(PAGE_BASIC_INFO, null);
				break;
			case PAGE_OTHER_INFO:
				showFragment(PAGE_UPLOAD_CREDIT, null);
				break;
			default:
				showFragment(PAGE_BASIC_INFO, null);
				break;
		}
	}

	public void pageDown(int page, Object argument) {
		switch (page) {
			case PAGE_UPLOAD_CREDIT:
				if ((PAGE_BASIC_INFO == mCurrentPage))
					showFragment(PAGE_UPLOAD_CREDIT, argument);
				break;
			case PAGE_OTHER_INFO:
				if (PAGE_UPLOAD_CREDIT == mCurrentPage)
					showFragment(PAGE_OTHER_INFO, argument);
				break;
		}
	}

	@Override
	public void onBackBtnPressed() {
		if (mCurrentPage == PAGE_BASIC_INFO) {
			FragmentManager fm = getSupportFragmentManager();
			BasicInfoFragment fragment = (BasicInfoFragment) fm.findFragmentByTag(BASIC_INFO_TAG);
			if (fragment != null) {
				fragment.onBackPressed();
			}else {
				finish();
			}
		} else {
			pageUp();
		}
	}

	@Override
	public void onBackPressed() {
		onBackBtnPressed();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			switch (mCurrentPage) {
				case PAGE_BASIC_INFO: {
					FragmentManager fm = getSupportFragmentManager();
					Fragment fragment = fm.findFragmentByTag(BASIC_INFO_TAG);
					fragment.onActivityResult(requestCode, resultCode, data);
					break;
				}
				case PAGE_UPLOAD_CREDIT: {
					FragmentManager fm = getSupportFragmentManager();
					Fragment fragment = fm.findFragmentByTag(UPLOAD_CREDIT_PAPER_TAG);
					fragment.onActivityResult(requestCode, resultCode, data);
					break;
				}
				case PAGE_OTHER_INFO: {
					FragmentManager fm = getSupportFragmentManager();
					Fragment fragment = fm.findFragmentByTag(OTHER_INFO_TAG);
					fragment.onActivityResult(requestCode, resultCode, data);
					break;
				}
			}
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		EventAgent.unregister(this);
		super.onDestroy();
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {

	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return null;
	}
}
